package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.UserDB;

import worklog.dto.ResponseDTO;
import worklog.dto.UserDTO;

@WebServlet("/addUser")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDB userDB;
	private ResponseDTO responder = new ResponseDTO();

	public AddUser() { super(); }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		userDB = new UserDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
		out.print(processRequest(request));
		userDB.close();
		out.close();
	}

	private String processRequest(HttpServletRequest request) {
		HttpSession session = request.getSession();

		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		
		int adminId = (Integer) session.getAttribute("userId");
		Boolean isAdmin = userDB.isAdmin(adminId);
		if (isAdmin == false) return responder.showError("Access denied!");

		int paramLength = request.getParameterMap().size(), userId;
		String userLogin, userEmail, userStatusStr;
		UserDTO user = new UserDTO();

    	if (paramLength > 0) {
			userLogin = request.getParameter("login");
			userEmail = request.getParameter("email");
			userStatusStr = request.getParameter("status");
			int userStatus = 1;
			try{ userStatus = Integer.parseInt(userStatusStr); } catch(NumberFormatException e){ }

			if (userLogin == null) return responder.showError("User login is empty!");
			if (userDB.checkUserLogin(userLogin)) return responder.showError("User login already exists");
			
			user.setLogin(userLogin);
			user.setEmail(userEmail);
			user.setStatus(userStatus);
			userId = userDB.addUser(user);
			if (userId != -1) {
				user.setId(userId);
				return user.toString();
			}
			return responder.showError("DB error");
    	}	
		return responder.showError();
	}

}
